const User = require('../models/User');
const db = require('../config/db');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
require('dotenv').config();

class UserController {
  // Register a new user
  static async register(req, res) {
    try {
      const { username, phone, password } = req.body;
      
      // Validate input
      if (!username || !phone || !password) {
        return res.status(400).json({ error: 'Username, phone, and password are required' });
      }
      
      // Validate phone format (simple validation)
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(phone)) {
        return res.status(400).json({ error: 'Invalid phone number format' });
      }
      
      // Check if user already exists
      const existingUser = await db.query(
        'SELECT * FROM users WHERE username = $1 OR phone = $2',
        [username, phone]
      );
      
      if (existingUser && existingUser.rows && existingUser.rows.length > 0) {
        return res.status(400).json({ error: 'User already exists' });
      }
      
      // Hash password
      const saltRounds = 10;
      const hashedPassword = await bcrypt.hash(password, saltRounds);
      
      // Create user
      const result = await db.query(
        'INSERT INTO users (username, phone, password_hash) VALUES ($1, $2, $3) RETURNING *',
        [username, phone, hashedPassword]
      );
      
      if (!result || !result.rows || result.rows.length === 0) {
        return res.status(500).json({ error: 'Failed to create user' });
      }
      
      const user = User.fromRow(result.rows[0]);
      
      // Generate JWT token
      const token = jwt.sign(
        { userId: user.id, username: user.username },
        process.env.JWT_SECRET,
        { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
      );
      
      res.status(201).json({
        message: 'User registered successfully',
        user: user.toJSON(),
        token
      });
    } catch (error) {
      console.error('Registration error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
  
  // Login user
  static async login(req, res) {
    try {
      const { phone, password } = req.body;
      
      // Validate input
      if (!phone || !password) {
        return res.status(400).json({ error: 'Phone and password are required' });
      }
      
      // Find user
      const result = await db.query(
        'SELECT * FROM users WHERE phone = $1',
        [phone]
      );
      
      if (!result || !result.rows || result.rows.length === 0) {
        return res.status(401).json({ error: 'Invalid credentials' });
      }
      
      const user = User.fromRow(result.rows[0]);
      
      // Check password
      const isPasswordValid = await bcrypt.compare(password, user.password_hash);
      
      if (!isPasswordValid) {
        return res.status(401).json({ error: 'Invalid credentials' });
      }
      
      // Generate JWT token
      const token = jwt.sign(
        { userId: user.id, username: user.username },
        process.env.JWT_SECRET,
        { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
      );
      
      res.json({
        message: 'Login successful',
        user: user.toJSON(),
        token
      });
    } catch (error) {
      console.error('Login error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
  
  // Get user profile
  static async getProfile(req, res) {
    try {
      const userId = req.userId; // Set by auth middleware
      
      const result = await db.query(
        'SELECT * FROM users WHERE id = $1',
        [userId]
      );
      
      if (!result || !result.rows || result.rows.length === 0) {
        return res.status(404).json({ error: 'User not found' });
      }
      
      const user = User.fromRow(result.rows[0]);
      
      res.json({
        user: user.toJSON()
      });
    } catch (error) {
      console.error('Get profile error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
}

module.exports = UserController;